package com.xiaoyu.lanling.feature.moment.fragment.detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.event.moment.detail.TryDeleteCommentEvent
import com.xiaoyu.lanling.feature.moment.controller.detail.CommentDetailListController
import com.xiaoyu.lanling.feature.moment.data.MomentAction
import com.xiaoyu.lanling.feature.moment.data.detail.CommentDetailListData
import com.xiaoyu.lanling.view.OnShowFragment
import kotlinx.android.synthetic.main.fragment_like_list.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CommentListFragment : OnShowFragment() {
    private lateinit var listController: CommentDetailListController

    companion object {

        val KEY_FEED_ID = "key_feed_id"

        fun newInstance(feedId: String): CommentListFragment {
            val args = Bundle()
            args.putString(KEY_FEED_ID, feedId)
            val fragment = CommentListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_comment_list, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initEvent()
        initData()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: TryDeleteCommentEvent) {
                val fid = arguments?.getString(KEY_FEED_ID) ?: ""
                MomentAction.deleteComment(Any(), event.cid, fid)
            }
        })
    }

    private fun initData() {
        activity?.let {
            val feedId = arguments?.getString(KEY_FEED_ID) ?: return
            listController = CommentDetailListController.create(it, CommentDetailListData(feedId), swipe_refresh_layout, recyclerview)
            listController.loadFirstPageData()
        }
    }
}